package com.cy.algorithm.lru;

/**
 * @param <T>
 * @author yuchen
 */
public class LruLinkedList<T> extends MyLinkedList<T> {

    static final int DEFAULT_MEMORY_SIZE = 8;
    int memorySize;

    private LruLinkedList() {
        this(DEFAULT_MEMORY_SIZE);
    }

    private LruLinkedList(int memorySize) {
        this.memorySize = memorySize;
    }

    /**
     * 放入元素
     *
     * @param data 要放入的数据
     */
    public void putValue(T data) {
        if (size >= memorySize) {
            removeLast();
        }
        put(data);
    }

    /**
     * 删除元素
     *
     * @return 移除的元素
     */
    public T removeValue() {
        return removeLast();
    }

    /**
     * 获取缓存
     *
     * @param index
     * @return
     */
    public T getValue(int index) {
        checkIndex(index);
        Node<T> pre = new Node<>(null, head);
        Node<T> curr = head;
        for (int i = 0; i < index; i++) {
            if (curr.next != null) {
                pre = curr;
                curr = curr.next;
            }
        }
        pre.next = curr.next;
        curr.next = head;
        head = curr;
        return curr.data;

    }


    public static void main(String[] args) {
        LruLinkedList<Integer> lruLinkedList = new LruLinkedList<>();
        for (int i = 0; i < 7; i++) {
            lruLinkedList.putValue(i);
        }
        System.out.println(lruLinkedList.toString());
        lruLinkedList.putValue(10);
        lruLinkedList.putValue(9);
        System.out.println(lruLinkedList.toString());
        lruLinkedList.putValue(9);
        System.out.println(lruLinkedList.toString());
        lruLinkedList.putValue(9);
        System.out.println(lruLinkedList.toString());
        lruLinkedList.getValue(3);
        System.out.println(lruLinkedList.toString());
        lruLinkedList.getValue(7);
        System.out.println(lruLinkedList.toString());
    }
}
